﻿using MediatR;
using Traceability.Commont.Domains.BatchManagementFiles;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.WhiteStripWeighingHtmlGroup;
using Traceability.Commont.Infrastructures.Interfaces;

namespace U.Enterprise.Api.Applications.ByProducts
{
    /// <summary>
    /// 副产分组
    /// </summary>
    public class ByproductsGroupHander : IRequestHandler<ByproductsGroupCommand, Resqults<WhiteGroupDTO>>
    {
        private readonly IBateRepository<BulkSlaughter> bule;
        private readonly IBateRepository<Byproduct> bypro;

        public ByproductsGroupHander(IBateRepository<BulkSlaughter> bule, IBateRepository<Byproduct> bypro)
        {
            this.bule = bule;
            this.bypro = bypro;
        }

        public async Task<Resqults<WhiteGroupDTO>> Handle(ByproductsGroupCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Resqults<WhiteGroupDTO>() { Code = 0 };
                int years = DateTime.Now.Year;
                int months = DateTime.Now.Month;
                if (request.Date != null)
                {
                    years = request.Date.Value.Year;
                    months = request.Date.Value.Month;
                }
                var list = (from a in bule.GetAll()
                            join b in bypro.GetAll() on a.DocumentsNo equals b.DocumentsNo
                            where (b.ByproductDate.Year == years && b.ByproductDate.Month == months)
                            group new { a, b } by new { b.ByproductDate.Day } into c
                            select new WhiteGroupDTO()
                            {
                                Nums = c.Sum(x => x.a.BulkSlaughterNum),
                                WeghitNums = c.Sum(x => x.b.byproductNum),
                                WightSum = c.Sum(x => x.b.byproductNetWeight),
                                day = c.Key.Day
                            }).ToList();
                result.Date = list;
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
